#include "randomgenerator.h"
#include <iostream>
#include <QFile>
#include <QtCore>

RandomGenerator::RandomGenerator() {
    qDebug()<< "Constructor for RandomGenerator Class was called";
}

/*
 * This function takes the input File strng and the stock code and reads the data to find out
 * if we have the completed data for the day to be displayed or not
 * returns true if we have the complete data, if there isn't complete data, it completes the file and returns true
 * any error returns a false
 * @param QString fileSting
 * @param QString stockCode
 */
bool RandomGenerator::generateRandom(QString fileString, QString stockCode) {
    QString CLOCK_FORMAT= "hh:mm:ss";
    QString DATE_FORMAT= "yyyy-MM-dd";
    QFile file(fileString);
    if (!file.open(QIODevice::ReadWrite)) {
        qDebug() << "File " << fileString << " cannot be opened in generateRandom function!" << endl;
        return false;
    }
    qDebug() << "File " << file.fileName() << " opened in generateRandom function";
    QTextStream in(&file);
    QString lastLine;
    while(!in.atEnd()) {
        lastLine = in.readLine();
    }
    file.close();

    //get the last time from the file
    QDateTime timeFromLastLine;
    QStringList fields = lastLine.split(",");

    if (fields.count() > 1) {
        timeFromLastLine = QDateTime::fromString(fields.at(2), "yyyy-MM-dd HH:mm:ss");
        if (timeFromLastLine.time() >= QTime::fromString(MARKET_CLOSE, CLOCK_FORMAT)) //Checking if we have the days complete data
            return true;
    }

    //Generate random data from the last line's time to the current time.
    if (!file.open(QIODevice::Append)) {
        qDebug() << "File " << fileString << " cannot be opened for appending!" << endl;
    }
    qDebug() << timeFromLastLine.time();
    if (timeFromLastLine.time().isNull()) {
        qDebug() << "There was no time from the file, hence setting time";
        timeFromLastLine.setTime(QTime::fromString(MARKET_OPEN, CLOCK_FORMAT));
        timeFromLastLine.setDate(QDateTime::currentDateTime().date());
    }
    QTextStream out(&file);

    //Seeding the random generator function
    //improve this by adding ASCII characters, and time?
    QTime time = QTime::currentTime();
    qsrand((uint)time.msec());

    QTime time1(timeFromLastLine.time().hour(), timeFromLastLine.time().minute(), timeFromLastLine.time().second());
    time1 = time1.addSecs(70);
    while (1) {

        int numberOfSecsToBeAdded = QString::number(((rand() % (MAX_SEC + 1)) + 0)).toInt();
        time1 = time1.addSecs(numberOfSecsToBeAdded);
        timeFromLastLine.setTime(time1);

        double price = QString::number(((rand() % (STOCK_PRICE_MAX)) + 0)).toDouble();
        double decimals = QString::number(((rand() % (STOCK_PRICE_DEC_MAX)) + 0)).toDouble();
        double randomStockPrice = (double)price + (double)(decimals / 10); //division will produce decimal most likely

        QString data;
        data.append(stockCode);
        data.append(",");
        QVariant var1(randomStockPrice);
        data.append(var1.toString());
        data.append(",");
        data.append(timeFromLastLine.date().toString(DATE_FORMAT));
        data.append(" ");
        data.append(timeFromLastLine.time().toString(CLOCK_FORMAT));
        data.append("\n");
        out << data;
        qDebug() << data << " has been written to file: " << fileString;
        if (time1 >= QTime::fromString(MARKET_CLOSE, CLOCK_FORMAT)) //Stock market closes at 4pm
            break;
    }
    file.flush();
    file.close();
    return true;
}

/* This is a slot which receives change from the combo box.
** Unsure if this is the right function to be implemented or not.
*/
void RandomGenerator::receiveChangeFromUI(QString stockCode) {
    qDebug() << "The stock code received into RM is = " << stockCode;
}
